<?php

namespace App\Models\Cruise;


use App\Library\Rms\RmsUserApi;
use App\Models\BaseModel;
use App\Models\Common\FsCompanyModel;
use App\Models\Common\FsCompanyUserModel;
use App\Models\Traits\KfSoftDeletes;
use App\Models\Traits\KfUid;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\Cache;

class CruiseCheckCompanyModel extends BaseModel
{
    use KfUid, KfSoftDeletes;

    protected $table    = 'cruise_check_company';
    protected $fillable = [
        'fsCompanyId',
        'companyManagerId',
        'kfManagerId',
        'status'
    ];

    const STATUS_OFF = 0;
    const STATUS_ON  = 1;

    const STATUS_TEXT = [
        self::STATUS_OFF => '停用',
        self::STATUS_ON  => '启用',
    ];

    // 供应商全量缓存
    const CACHE_COMPANY_LISTS_CACHE = 'companyListsCache';

    /**
     * @return HasOne FsCompanyModel
     */
    public function fsCompanyRel(): HasOne
    {
        return $this->hasOne(FsCompanyModel::class, 'id', 'fsCompanyId');
    }

    /**
     * @return HasOne FsCompanyUserModel
     */
    public function fsCompanyUserRel(): HasOne
    {
        return $this->hasOne(FsCompanyUserModel::class, 'rmsUserId', 'companyManagerId');
    }

    /**
     * @return HasOne FsCompanyUserModel
     */
    public function kfFsCompanyUserRel(): HasOne
    {
        return $this->hasOne(FsCompanyUserModel::class, 'rmsUserId', 'kfManagerId');
    }

    /**
     * @return HasMany
     */
    public function cruiseCheckSelfTaskCompanyMappingsRel(): HasMany
    {
        return $this->hasMany(CruiseCheckSelfTaskCompanyMappingModel::class, "cruiseCheckCompanyId", "id");
    }

    /**
     * @return HasMany
     */
    public function cruiseCheckSelfDetailRel(): HasMany
    {
        return $this->hasMany(CruiseCheckSelfDetailModel::class, "cruiseCheckCompanyId", "id");
    }

    /**
     * 通过id获取
     * @param int $fsCompanyId
     * @return array
     */
    public static function getDataById(int $cruiseCheckCompanyId): array
    {
        return self::companyListsCache()[$cruiseCheckCompanyId] ?? [];
    }

    public static function forgetCompanyListsCache()
    {
        return Cache::forget(self::CACHE_COMPANY_LISTS_CACHE);
    }

    /**
     * 全量的缓存
     * @return mixed
     */
    private static function companyListsCache(): array
    {
        return Cache::remember(self::CACHE_COMPANY_LISTS_CACHE, 300, function () {

            $userIds = [];
            self::query()->select('companyManagerId', 'kfManagerId')->get()->each(function ($item) use (&$userIds) {
                $userIds[] = $item->companyManagerId;
                $userIds[] = $item->kfManagerId;
            });
            $userIds = array_values(array_unique($userIds));

            $userInfos = collect((new RmsUserApi())->getUserInfoByIds($userIds, ['id', 'username'])['data'] ?? [])
                ->keyBy('id');

            return self::query()
                       ->with('fsCompanyRel', 'kfFsCompanyUserRel')
                       ->get()
                       ->map(function ($item) use ($userInfos) {

                           $fsCompanyUserRel = FsCompanyUserModel::query()
                                                                 ->where('rmsUserId', $item->companyManagerId)
                                                                 ->where('ext', FsCompanyUserModel::EXT_OUT)
                                                                 ->first();

                           return [
                               'id'             => $item->id,
                               'fsCompanyId'    => $item->fsCompanyId,
                               'kfManagerId'    => $item->kfManagerId,
                               'status'         => $item->status,
                               'fsCompany'      => [
                                   'departmentId' => $item->fsCompanyRel->departmentId,
                                   'name'         => $item->fsCompanyRel->name,
                               ],
                               'companyManager' => [
                                   'rmsUserId' => $fsCompanyUserRelRmsUserId = $fsCompanyUserRel['rmsUserId'] ?? 0,
                                   'feishuId'  => $fsCompanyUserRel['feishuId'] ?? '',
                                   'name'      => $userInfos[$fsCompanyUserRelRmsUserId]['username'] ?? ($fsCompanyUserRel['name'] ?? ''),
                                   'phone'     => $fsCompanyUserRel['phone'] ?? '',
                               ],
                               'kfManager'      => [
                                   'rmsUserId' => $item->kfFsCompanyUserRel['rmsUserId'] ?? 0,
                                   'feishuId'  => $item->kfFsCompanyUserRel['feishuId'] ?? '',
                                   'name'      => $userInfos[$item->kfFsCompanyUserRel['rmsUserId'] ?? 0]['username'] ?? ($item->kfFsCompanyUserRel['name'] ?? ''),
                                   'phone'     => $item->kfFsCompanyUserRel['phone'] ?? '',
                               ],
                           ];
                       })->keyBy('id')->toArray();
        });
    }

    public static function getOrgIdById(int $id): int
    {
        $fsCompanyId = (int)self::query()->where('id', $id)->value('fsCompanyId');
        if (!$fsCompanyId) {
            return 0;
        }

        return (int)FsCompanyModel::query()->where('id', $fsCompanyId)->value('organizationId');
    }
}
